#!/usr/bin/env python

import web
import os
import config
from log import log
from base import adminAction

'''
User controller: producing install views.
'''
class installAction(adminAction):
    def __init__(self, name = 'Install'):
        adminAction.__init__(self, name, chkInstall=False)
        self.status = 0

    def index(self):
        if self.isInstalled():
            return web.seeother('/')

        return self.display('install')

    def do(self):
        if self.isInstalled():
            return web.seeother('/')
        else:
            if not os.path.exists(config.DATA_DIR):
                os.makedirs(config.DATA_DIR)

            import sqlite3 as db
            conn = db.connect(self.database)
            cursor = conn.cursor()
            sqlList = [
            # Enabled foreign key
            """
            PRAGMA FOREIGN_KEYS=ON;
            """,

            # User table 
            """
            CREATE TABLE 'user' (
              'id' INTEGER PRIMARY KEY,
              'email' VARCHAR(128),
              'nickname' VARCHAR(128),
              'firstname' VARCHAR(64),
              'lastname' VARCHAR(64),
              'gender' INT,
              'passwd' VARCHAR(64),
              'avatur' BLOB,
              'lastLoginTime' TIMESTAMP
             );
            """,

            # Category table
            """
            CREATE TABLE 'category' (
              'id' INTEGER PRIMARY KEY,
              'name' VARCHAR(128)
             );
            """,

            # News table
            """
            CREATE TABLE 'news' (
              'id' INTEGER PRIMARY KEY,
              'name' VARCHAR(128),
              'content' TEXT,
              'category' INT,
              'createTime' TIMESTAMP,
              'thumbnail' BLOB,
              'status' INT,
              FOREIGN KEY(category) REFERENCES category(id)
             );
            """,

            # Album table
            """
            CREATE TABLE 'album' (
              'id' INTEGER PRIMARY KEY,
              'cover' BLOB,
              'createTime' TIMESTAMP,
              'desc' TEXT
             );
            """,

            # Image table
            """
            CREATE TABLE 'image' (
              'id' INTEGER PRIMARY KEY,
              'url' VARCHAR(1024),
              'createTime' TIMESTAMP,
              'album' INT,
              'desc' TEXT,
              FOREIGN KEY(album) REFERENCES album(id)
             );
            """,


            # Mandotory default records
            """
            INSERT INTO category (id, name) values (
                1,
                'Default'
            );
            """,

            """
            INSERT INTO album (id, desc) values (
                1,
                'Default album'
            );
            """,
            ]


            for sql in sqlList:
                self.status = cursor.execute(sql)
            conn.commit()
            conn.close()

            if self.status:
                return self.success(msg='Install successfully.')
            else:
                return self.error(msg='Install failed.')

    def GET(self, name):
        # Install: index page
        if not name:
            return self.index()
        # Install: perform installation
        elif name == 'do':
            return self.do()
        # Install: page not found
        else:
            return self.notFound()
